#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2, urllib, re

def _to_gbk(s):
    """
    
    Arguments:
    - `s`:
    """
    return unicode(s, "utf8").encode("gbk")

def _to_utf8(s):
    """
    
    Arguments:
    - `s`:
    """
    return unicode(s, "gbk").encode("utf8")

class LyricEngineSogou:
    def __init__(self):
        """
        
        Arguments:
        - `self`:
        """
    def request_lyric(self, artist, title):
        """ the encoding of artist and title is utf8
        Arguments:
        - `self`:
        - `artist`:
        - `title`:
        """
        # make the real search url
        url = ('http://mp3.sogou.com/gecisearch.so?query='
               + urllib.quote_plus('%s %s' % (_to_gbk(artist),
                                              _to_gbk(title))))

        # print url
        try:
            headers = {
                'User-Agent': "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8" }
            req = urllib2.Request(url, "", headers)
            res = urllib2.urlopen(req)
            r = res.read()

            print r
        except:
            return []
        p = re.compile(r'href=\"(downlrc\.jsp.*?)\"')
        res = []
        for m in p.finditer(r):
            res.append('http://mp3.sogou.com/' + m.group(1))

        return res

    def download_lrc(self, url):
        """
        
        Arguments:
        - `self`:
        - `url`:
        """
        try:
            h = urllib.urlopen(url)
            r = h.read()
            h.close()
        except:
            return ""
        return _to_utf8(r)


if __name__ == '__main__':
    sogou = LyricEngineSogou()
    urls = sogou.request_lyric('James Blunt', "You're Beautiful")
    if len(urls) == 0:
        print "not found"
    else:
        for url in urls:
            print url
        print "the first one is:"
        print sogou.download_lrc(urls[0])
